﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using NetDon.OA.Business;
using NetDon.OA.Interface.Admin;
using NetDon.OA.Interface.Configuration;
using NetDon.OA.Portal.Constants;
using NetDon.Utilities;
using NineRays.WebControls;

namespace NetDon.OA.Portal.Admin
{
    [Command(ButtonConstants.CommandNames.CreateCompany, ButtonConstants.CommandImages.CreateRoot, Order = 0, CausesValidation = false)]
    [Command(ButtonConstants.CommandNames.CreateDepartment, ButtonConstants.CommandImages.CreateRoot, Order = 1, CausesValidation = false)]
    [Command(ButtonConstants.CommandNames.Save, ButtonConstants.CommandImages.Save, Order = 2, CausesValidation = true)]
    [Command(ButtonConstants.CommandNames.Delete, ButtonConstants.CommandImages.Delete, Order = 3, CausesValidation = false)]

    [Navigation("组织架构管理", "组织架构管理")]

    [PageTabber(Index = 0, NavigateUrl = "~/Admin/CompanyConfig.aspx", Title = "组织架构管理", Type = typeof(CompanyConfig))]
    [PageTabber(Index = 1, NavigateUrl = "~/Admin/PositionConfig.aspx", Title = "岗位管理", Type = typeof(PositionConfig))]
    public partial class CompanyConfig : PageBase
    {
        public Guid Id
        {
            get { return ViewState["Id"] != null ? (Guid)ViewState["Id"] : Guid.Empty; }

            set { ViewState["Id"] = value; }
        }

        public Guid? ParentID
        {
            get { return ViewState["ParentID"] != null ? (Guid?)ViewState["ParentID"] : null; }

            set
            {
                ViewState["ParentID"] = value == Guid.Empty ? null : value;
            }
        }
        public Guid? ParentCompanyID
        {
            get { return ViewState["ParentCompanyID"] != null ? (Guid?)ViewState["ParentCompanyID"] : null; }

            set
            {
                ViewState["ParentCompanyID"] = value == Guid.Empty ? null : value;
            }
        }
        public NodeType CurrentNodeType
        {
            get { return ViewState["CurrentNodeType"] != null ? (NodeType)ViewState["CurrentNodeType"] : NodeType.Company; }

            set { ViewState["CurrentNodeType"] = value; }
        }
        public NodeType NewNodeType
        {
            get { return ViewState["NewNodeType"] != null ? (NodeType)ViewState["NewNodeType"] : NodeType.Root; }

            set { ViewState["NewNodeType"] = value; }
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                ControlHelper.SetFreeTextBoxEditor(txtDescription);
                this.pnlCompanyInfo.Visible = false;
                BindControls();
                ShowButtons();

            }
        }

        private void ShowButtons()
        {
            if (Id == Guid.Empty)
            {
                CommandButtons[ButtonConstants.CommandNames.Delete].Visible = false;
                CommandButtons[ButtonConstants.CommandNames.CreateDepartment].Visible = true;
                if (CurrentNodeType == NodeType.Root && ParentID == null && NewNodeType == NodeType.Root)
                {
                    CommandButtons[ButtonConstants.CommandNames.CreateDepartment].Visible = false;
                    CommandButtons[ButtonConstants.CommandNames.CreateCompany].Visible = true;
                    CommandButtons[ButtonConstants.CommandNames.Save].Visible = false;
                }
                else
                {
                    CommandButtons[ButtonConstants.CommandNames.CreateCompany].Visible = true;
                    CommandButtons[ButtonConstants.CommandNames.Save].Visible = true;
                    if (CurrentNodeType == NodeType.Department && NewNodeType == NodeType.Department)
                        CommandButtons[ButtonConstants.CommandNames.CreateCompany].Visible = false;
                }

            }
            else
            {
                CommandButtons[ButtonConstants.CommandNames.Delete].Visible = true;

                CommandButtons[ButtonConstants.CommandNames.CreateCompany].Visible = true;
                if (CurrentNodeType == NodeType.Department )
                    CommandButtons[ButtonConstants.CommandNames.CreateCompany].Visible = false;
                CommandButtons[ButtonConstants.CommandNames.CreateDepartment].Visible = true;
                CommandButtons[ButtonConstants.CommandNames.Save].Visible = true;
            }


        }

        private void BindControls()
        {
            BindCompany();

        }

        private void BindCompany()
        {
            var service = ServiceContainer.GetService<ICompanyService>();
            var rootCategories = service.GetRootCompanies();
            treeCompany.Nodes.Clear();
            //add root company
            treeCompany.Nodes.Add(CreateRootNode());
            for (int i = 0; i < rootCategories.Count; i++)
            {
                treeCompany.Nodes[0].ChildNodes.Add(CreateCompanyTreeNode(rootCategories[i]));
            }

            treeCompany.Nodes[0].Text =
                Server.HtmlEncode(SystemConfiguration.RootCompanyName);
            treeCompany.Nodes[0].PopulateNodesOnDemand = rootCategories.Count > 0 ? true : false;
            treeCompany.SelectedNode = treeCompany.Nodes[0];
            Id = Guid.Empty;
            ParentID = null;
            CurrentNodeType = NodeType.Root;
            NewNodeType = NodeType.Root;
        }

        private FlyTreeNode CreateRootNode()
        {
            return new FlyTreeNode(
                            Server.HtmlEncode(SystemConfiguration.RootCompanyName),
                            Guid.Empty.ToString())
            {
                NodeTypeID = NodeType.Root.ToString(),
                ImageUrl = ApplicationImages.TreeNodeClosed,
                SelectedImageUrl = ApplicationImages.TreeNodeOpened,
                Expanded = true,
                ExpandLevel = 999,
                Tag = -1
            };
        }

        protected void treeCompany_PopulateNodes(object sender, FlyTreeNodeEventArgs e)
        {
            this.btnModify_Click(null,null);
            if (e.Node.ChildNodes.Count <= 0)
            {
                LoadChildNodes(e.Node);
            }
        }

        private FlyTreeNode CreateCompanyTreeNode(CompanyData companyData)
        {
            return new FlyTreeNode(
                            Server.HtmlEncode(companyData.CompanyName),
                            companyData.CompanyId.ToString())
            {
                NodeTypeID = NodeType.Company.ToString(),
                PopulateNodesOnDemand = companyData.HasChildren,
                ImageUrl = ApplicationImages.TreeNodeClosed,
                SelectedImageUrl = ApplicationImages.TreeNodeOpened,
                Tag = companyData.NodeLevel,
    
            };
        }
        private FlyTreeNode CreateDepartmentTreeNode(DepartmentData departmentData)
        {
            return new FlyTreeNode(
                            Server.HtmlEncode(departmentData.DepartmentName),
                            departmentData.DepartmentId.ToString())
            {
                NodeTypeID = NodeType.Department.ToString(),
                PopulateNodesOnDemand = departmentData.HasChildren,
                ImageUrl = ApplicationImages.DepartNodeClosed,
                SelectedImageUrl = ApplicationImages.DepartNodeOpened,
                Tag = departmentData.NodeLevel,
              
            };
        }
        private void LoadChildNodes(FlyTreeNode node)
        {
         
            if (node.ChildNodes.Count <= 0)
            {
                //load companies
                var service = ServiceContainer.GetService<ICompanyService>();
                if(node.Value .ToGuid() ==Guid.Empty)
                return;
                if(node.NodeTypeID !=NodeType.Department.ToString())
                {
                    var childCompanies = (CompanyDataCollection)service.GetCompany(node.Value.ToGuid()).GetChildren();
                    for (int i = 0; i < childCompanies.Count; i++)
                    {
                        node.ChildNodes.Add(CreateCompanyTreeNode(childCompanies[i]));

                    }
                }
               

                ////load deparments
                var childDepartments = ServiceContainer.GetService<IDepartmentService>().GetRootDepartments(node.Value.ToGuid());
                for (int i = 0; i < childDepartments.Count; i++)
                {
                    node.ChildNodes.Add(CreateDepartmentTreeNode(childDepartments[i]));

                }
            }
        }

        private void CreateCompany()
        {
            //parent Category is Root
            ClearControl();
            Id = Guid.Empty;
            ParentID = treeCompany.SelectedNode.Value.ToGuid();
            txtParentName.Text = treeCompany.SelectedNode.Text.Trim();
            pnlCompanyInfo.Visible = true;
            pnlDepartmentInfo.Visible = false;

            this.NewNodeType = NodeType.Company;
            if (this.treeCompany.SelectedNode.Tag.ToString() == "-1")
                txtCompanyNodeLevel.Text = "1";
            else
            {
                txtCompanyNodeLevel.Text = (this.treeCompany.SelectedNode.Tag.ToString().ToInt32() + 1).ToString();
            }
        }

        private void CreateDepartment()
        {
            ClearControl();
            Id = Guid.Empty;

            txtParentCompanyOrDepartmentName.Text = treeCompany.SelectedNode.Text.Trim();
            pnlCompanyInfo.Visible = false;
            pnlDepartmentInfo.Visible = true;

            this.NewNodeType = NodeType.Department;
            if (this.treeCompany.SelectedNode.NodeTypeID == NodeType.Company.ToString())
            {
                txtDepartmentNodeLevel.Text = "1";
                ParentCompanyID = treeCompany.SelectedNode.Value.ToGuid();
                ParentID = null;
            }
            else
            {
                ParentID = treeCompany.SelectedNode.Value.ToGuid();
                txtDepartmentNodeLevel.Text = (this.treeCompany.SelectedNode.Tag.ToString().ToInt32() + 1).ToString();
            }

        }

        protected void ClearControl()
        {
            //clear company
            txtParentName.Text = string.Empty;
            txtCompanyName.Text = txtCompanyCode.Text = txtDescription.Text = txtEmail.Text = txtFax.Text = txtPostalCode.Text = txtPhone.Text = txtWebsite.Text = txtAddress.Text = string.Empty;
            txtCompanyNodeLevel.Text = string.Empty;
            txtPresident.Text = string.Empty;
            //clear department
            txtDepartmentName.Text = string.Empty;
            txtDepartmentCode.Text = string.Empty;
            txtDepartDesc.Text = string.Empty;
            txtParentName.Text = string.Empty;
            txtDepartFax.Text = string.Empty;
            txtDepartAddress.Text = string.Empty;
            txtDepartTelephone.Text = string.Empty;
            txtDepartmentNodeLevel.Text = string.Empty;
            txtDepartManager.Text = string.Empty;
        }

        protected void btnModify_Click(object sender, EventArgs e)
        {

            if (treeCompany.SelectedNode.NodeTypeID == NodeType.Root.ToString())
            {
                Id = Guid.Empty;
                ParentID = null;
                CurrentNodeType = NodeType.Root;
                NewNodeType = NodeType.Root;
                pnlCompanyInfo.Visible = false;
                pnlDepartmentInfo.Visible = false;
            }
            else if (this.treeCompany.SelectedNode.NodeTypeID == NodeType.Company.ToString())
            {
                pnlCompanyInfo.Visible = true;
                pnlDepartmentInfo.Visible = false;
                NewNodeType = NodeType.Company;

            }
            else
            {
                pnlCompanyInfo.Visible = false;
                pnlDepartmentInfo.Visible = true;
                NewNodeType = NodeType.Department;
            }
            ShowButtons();
            InitCompanyOrDepartment();

        }

        private void InitCompanyOrDepartment()
        {
            if (this.treeCompany.SelectedNode.NodeTypeID == NodeType.Company.ToString())
            {
                var service = ServiceContainer.GetService<ICompanyService>();
                var company = service.GetCompany(treeCompany.SelectedNode.Value.ToGuid());
                if (company != null)
                {
                    txtCompanyName.Text = company.CompanyName;
                    txtCompanyCode.Text = company.CompanyCode;
                    //add more 
                    if (!company.ParentId.HasValue)
                        txtParentName.Text = SystemConfiguration.RootCompanyName;
                    else
                        txtParentName.Text = service.GetCompany(company.ParentId.Value).CompanyName;

                    txtFax.Text = company.Fax;
                    txtPostalCode.Text = company.PostCode;
                    txtWebsite.Text = company.Website;
                    txtDescription.Text = company.CompanyDesc;
                    txtEmail.Text = company.Email;
                    txtAddress.Text = company.Address;
                    txtPhone.Text = company.Telephone;
                    txtCompanyNodeLevel.Text = company.NodeLevel.ToString();
                    txtPresident.Text  = company.CEO;
                    Id = treeCompany.SelectedNode.Value.ToGuid();
                    ParentID = company.ParentId;
                    CurrentNodeType = NodeType.Company;
                    ShowButtons();
                }
            }
            else if (this.treeCompany.SelectedNode.NodeTypeID == NodeType.Department.ToString())
            {
                var service = ServiceContainer.GetService<IDepartmentService>();
                var department = service.GetDepartment(treeCompany.SelectedNode.Value.ToGuid());
                if (department != null)
                {
                    txtDepartmentName.Text = department.DepartmentName;
                    txtDepartmentCode.Text = department.DepartmentCode;
                    txtDepartDesc.Text = department.DepartmentDesc;

                    if (department.ParentId.HasValue)
                        txtParentCompanyOrDepartmentName.Text = service.GetDepartment(department.ParentId.Value).DepartmentName;
                    else if(department.CompanyId.HasValue)
                        txtParentCompanyOrDepartmentName.Text = ServiceContainer.GetService<ICompanyService>().GetCompany(department.CompanyId.Value).CompanyName;

                    txtDepartFax.Text = department.Fax;
                    txtDepartAddress.Text = department.Address;
                    txtDepartTelephone.Text = department.Telephone;
                    txtDepartmentNodeLevel.Text = department.NodeLevel.ToString();
                    txtDepartManager.Text = department.Manager;
                    Id = treeCompany.SelectedNode.Value.ToGuid();
                    ParentID = department.ParentId;
                    ParentCompanyID = department.CompanyId;
                    CurrentNodeType = NodeType.Department;
                    ShowButtons();
                }
            }

        }
        private void SaveDepartment()
        {
            txtDepartmentNodeLevel.Text = (this.treeCompany.SelectedNode.Tag.ToString().ToInt32()).ToString();
            var data = new DepartmentData()
            {
                ParentId = ParentID,
                DepartmentId = Guid.NewGuid(),
                DepartmentCode = this.txtDepartmentCode.Text.Trim(),
                DepartmentName = this.txtDepartmentName.Text.Trim(),
                Manager = this.txtDepartManager.Text.Trim(),
                Address = this.txtDepartAddress.Text.Trim(),
                DepartmentDesc = this.txtDepartDesc.Text.Trim(),
                CompanyId = ParentCompanyID,
                Fax = this.txtDepartFax.Text.Trim(),
                Telephone = this.txtDepartTelephone.Text.Trim(),
                NodeLevel = Convert.ToInt32(this.txtDepartmentNodeLevel.Text)
            };
           
           
            if (Id != Guid.Empty) data.DepartmentId = Id;
            var service = ServiceContainer.GetService<IDepartmentService>();
            bool result = Id == Guid.Empty ? service.AddDepartment(data) : service.ModifyDepartment(data);
            if (result)
            {
                if (Id == Guid.Empty)
                {
                    var node = CreateDepartmentTreeNode(data);
                    if (ParentID.HasValue)
                    {
                        var parentNode = treeCompany.FindByValue(ParentID.Value.ToString());
                        parentNode.ChildNodes.Add(node);
                    }
                    else if (ParentCompanyID != null)
                    {
                        var parentNode = treeCompany.FindByValue(ParentCompanyID.Value.ToString());
                        parentNode.ChildNodes.Add(node);
                    }

                    treeCompany.SelectedNode = node;
                    Id = data.DepartmentId;
                    CurrentNodeType = NodeType.Company;
                }
                else
                {
                    treeCompany.FindByValue(Id.ToString()).Text = Server.HtmlEncode(data.DepartmentName);
                }
                ShowButtons();
                base.Success("保存部门成功！");
            }
            else
            {
                ShowDataError(data);
            }
        }
        private void SaveCompany()
        {
            var data = new CompanyData()
                           {
                               ParentId = ParentID,
                               CompanyCode = this.txtCompanyCode.Text.Trim(),
                               CompanyName = this.txtCompanyName.Text.Trim(),
                               Address = this.txtAddress.Text.Trim(),
                               CompanyDesc = this.txtDescription.Text.Trim(),
                               CompanyId = Guid.NewGuid(),
                               Email = this.txtEmail.Text.Trim(),
                               Fax = this.txtFax.Text.Trim(),
                               Website = this.txtWebsite.Text.Trim(),
                               PostCode = this.txtPostalCode.Text.Trim(),
                               Telephone = this.txtPhone.Text.Trim(),
                               NodeLevel = Convert.ToInt32(this.txtCompanyNodeLevel.Text),
                               CEO = txtPresident.Text
                           };
            if (Id != Guid.Empty) data.CompanyId = Id;
            var service = ServiceContainer.GetService<ICompanyService>();
            bool result = Id == Guid.Empty ? service.AddCompany(data) : service.ModifyCompany(data);
            if (result)
            {
                if (Id == Guid.Empty)
                {
                    var node = CreateCompanyTreeNode(data);
                    if (ParentID.HasValue)
                    {
                        var parentNode = treeCompany.FindByValue(ParentID.Value.ToString());
                        parentNode.ChildNodes.Add(node);
                    }
                    else
                    {
                        treeCompany.Nodes[0].ChildNodes.Add(node);
                    }
                    treeCompany.SelectedNode = node;
                    Id = data.CompanyId;
                    CurrentNodeType = NodeType.Company;
                }
                else
                {
                    treeCompany.FindByValue(Id.ToString()).Text = Server.HtmlEncode(data.CompanyName);
                }
                ShowButtons();
                base.Success("保存公司成功！");
            }
            else
            {
                ShowDataError(data);
            }
        }

        protected override void OnCommand(CommandEventArgs args)
        {
            var service = ServiceContainer.GetService<ICompanyService>();
            var departmentService = ServiceContainer.GetService<IDepartmentService>();
            switch (args.CommandName)
            {
                case ButtonConstants.CommandNames.Delete:
                    {
                        var companyId = treeCompany.SelectedNode.Value.ToGuid();
                        if(CurrentNodeType ==NodeType.Company)
                        {
                            if (service.CheckCompanyUsed(companyId))
                            {
                                //"The Company  '{0}' cannot be deleted. There are products assigned to the category!",
                                Alert(
                                    string.Format("公司{0}不能被删除，请先删除下面的子公司或部门。", treeCompany.SelectedNode.Text));
                                return;
                            }
                        }
                        else
                        {
                            if (departmentService.CheckDepartmentUsed(companyId))
                            {
                              
                                Alert(
                                    string.Format("部门{0}不能被删除，请先删除下面的子部门或人员。", treeCompany.SelectedNode.Text));
                                return;
                            }
                            
                        }
                       
                        string  selectedNode = string.Empty;
                        if (CurrentNodeType == NodeType.Company ? service.RemoveCompany(companyId) : departmentService.RemoveDepartment(companyId))
                        {
                            if (treeCompany.SelectedNode.Parent != null)
                            {

                                FlyTreeNode parentNode = treeCompany.SelectedNode.Parent;
                               
                                treeCompany.SelectedNode.Parent.ChildNodes.Remove(
                              treeCompany.SelectedNode);
                                if (parentNode.ChildNodes.Count > 0)
                                    selectedNode = parentNode.ChildNodes[0].Value;
                                else
                                    selectedNode = parentNode.Value;
                            }
                            else
                            {
                            
                                selectedNode = treeCompany.Nodes[0].ChildNodes[0].Value;
                                treeCompany.Nodes[0].ChildNodes.Remove(treeCompany.SelectedNode);
                            }
                         
                            Id = Guid.Empty;
                            ClearControl();
                            if (selectedNode == string.Empty)
                                treeCompany.SelectedNode = treeCompany.Nodes[0];
                            else
                            treeCompany.SelectedNode = treeCompany.FindByValue(selectedNode);
    
                        }
                        btnModify_Click(null, null);
                    }
                    break;


                case ButtonConstants.CommandNames.CreateDepartment:
                    CreateDepartment();
                    ShowButtons();
                    break;
                case ButtonConstants.CommandNames.CreateCompany:
                    CreateCompany();
                    ShowButtons();
                    break;
                case ButtonConstants.CommandNames.Save:
                    if (NewNodeType == NodeType.Company&&(CurrentNodeType == NodeType.Company||CurrentNodeType ==NodeType.Root))
                    {
                        SaveCompany();
                    }
                    else
                    {
                        SaveDepartment();
                    }


                    break;
            }
        }


    }

}
